package org.dromara.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.admin.domain.*;
import org.dromara.admin.domain.vo.ProductVo;
import org.dromara.admin.enums.CustomerTypeEnum;
import org.dromara.admin.enums.TemplateCategoryEnum;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.dromara.admin.domain.bo.OrderProductPriceBo;
import org.dromara.admin.domain.vo.OrderProductPriceVo;
import org.dromara.admin.mapper.OrderProductPriceMapper;
import org.dromara.admin.service.IOrderProductPriceService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 订单产品价格记录（存储一客一价和开单次数）Service业务层处理
 *
 * @author Lion Li
 * @date 2025-10-10
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class OrderProductPriceServiceImpl implements IOrderProductPriceService {

    private final OrderProductPriceMapper baseMapper;

    /**
     * 查询订单产品价格记录（存储一客一价和开单次数）
     *
     * @param id 主键
     * @return 订单产品价格记录（存储一客一价和开单次数）
     */
    @Override
    public OrderProductPriceVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询订单产品价格记录（存储一客一价和开单次数）列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 订单产品价格记录（存储一客一价和开单次数）分页列表
     */
    @Override
    public TableDataInfo<OrderProductPriceVo> queryPageList(OrderProductPriceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<OrderProductPrice> lqw = buildQueryWrapper(bo);
        Page<OrderProductPriceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询产品价格记录列表含关联信息
     *
     * @param bo        查询条件(自带客户id)
     * @param pageQuery 分页参数
     * @return
     */
    @Override
    public TableDataInfo<OrderProductPriceVo> queryPageAllList(OrderProductPriceBo bo, PageQuery pageQuery) {
        MPJLambdaWrapper<OrderProductPrice> mpjWrapper = new MPJLambdaWrapper<OrderProductPrice>()
            .selectAll(OrderProductPrice.class)
            .selectAssociation(Product.class, OrderProductPriceVo::getProductInfo, a -> a
                .association(ProductCategory.class, ProductVo::getProductCategoryInfo)
                .association(ProductGroup.class, ProductVo::getProductGroupInfo))
            .selectAssociation(Customer.class, OrderProductPriceVo::getCustomerInfo)
            .selectAssociation(Supplier.class, OrderProductPriceVo::getSupplierInfo)
            .leftJoin(Product.class, Product::getId, OrderProductPrice::getProductId)
            .leftJoin(ProductCategory.class, ProductCategory::getId, Product::getCategoryId)
            .leftJoin(ProductGroup.class, ProductGroup::getId, Product::getGroupId)
            .leftJoin(Customer.class, Customer::getId, OrderProductPrice::getCustomerId)
            .leftJoin(Supplier.class, Supplier::getId, OrderProductPrice::getCustomerId)
            .orderByDesc(OrderProductPrice::getOrderCount).orderByDesc(OrderProductPrice::getOrderProductCount)
            .eq(bo.getProductId() != null, OrderProductPrice::getProductId, bo.getProductId())
            .eq(bo.getCustomerId() != null, OrderProductPrice::getCustomerId, bo.getCustomerId())
            .eq(bo.getCategoryId() != null, Product::getCategoryId, bo.getCategoryId())
            .eq(bo.getGroupId() != null, Product::getGroupId, bo.getGroupId())
            .like(StringUtils.isNotBlank(bo.getName()), Product::getName, bo.getName());
        Page<OrderProductPriceVo> result = baseMapper.selectJoinPage(pageQuery.build(), OrderProductPriceVo.class, mpjWrapper);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的订单产品价格记录（存储一客一价和开单次数）列表
     *
     * @param bo 查询条件
     * @return 订单产品价格记录（存储一客一价和开单次数）列表
     */
    @Override
    public List<OrderProductPriceVo> queryList(OrderProductPriceBo bo) {
        LambdaQueryWrapper<OrderProductPrice> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OrderProductPrice> buildQueryWrapper(OrderProductPriceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<OrderProductPrice> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(OrderProductPrice::getId);
        lqw.eq(bo.getEmployeeId() != null, OrderProductPrice::getEmployeeId, bo.getEmployeeId());
        lqw.eq(bo.getProductId() != null, OrderProductPrice::getProductId, bo.getProductId());
        lqw.eq(bo.getCustomerId() != null, OrderProductPrice::getCustomerId, bo.getCustomerId());
        lqw.eq(bo.getCustomerType() != null, OrderProductPrice::getCustomerType, bo.getCustomerType());
        lqw.eq(bo.getProductPrice() != null, OrderProductPrice::getProductPrice, bo.getProductPrice());
        lqw.eq(bo.getOrderCount() != null, OrderProductPrice::getOrderCount, bo.getOrderCount());
        return lqw;
    }

    /**
     * 新增订单产品价格记录（存储一客一价和开单次数）
     *
     * @param bo 订单产品价格记录（存储一客一价和开单次数）
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(OrderProductPriceBo bo) {
        OrderProductPrice add = MapstructUtils.convert(bo, OrderProductPrice.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改订单产品价格记录（存储一客一价和开单次数）
     *
     * @param bo 订单产品价格记录（存储一客一价和开单次数）
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OrderProductPriceBo bo) {
        OrderProductPrice update = MapstructUtils.convert(bo, OrderProductPrice.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OrderProductPrice entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除订单产品价格记录（存储一客一价和开单次数）信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    /**
     * 根据产品ID和客户ID查询订单产品价格记录
     *
     * @param productId  产品ID
     * @param customerId 客户ID
     * @param orderType  订单类型
     * @return 订单产品价格记录
     */
    @Override
    public OrderProductPrice queryByProductIdAndCustomerIdAndOrderType(Long productId, Long customerId, TemplateCategoryEnum orderType) {
        OrderProductPrice orderProductPrice = baseMapper.selectOne(new LambdaQueryWrapper<OrderProductPrice>()
            .eq(OrderProductPrice::getProductId, productId)
            .eq(OrderProductPrice::getCustomerId, customerId)
            .eq(OrderProductPrice::getOrderType, orderType));
        if (BeanUtil.isEmpty(orderProductPrice)) {
            return null;
        }
        return orderProductPrice;
    }
}
